<template>
  <div v-if="hasLink" class="linkSection">
    <div v-if="!isDown" class="linkExternalContainer">
      <div v-for="l in LinkList" :key="l.data?.linkId" class="link">
        <div class="link-header">
          <span class="provider-name">链接提供者: {{ l.userName }}</span>
          <img
              v-if="!isNull(l.userHeadPortraitUrl)"
              :src="`${globalConst.staticResourceUrl}img/${l.userHeadPortraitUrl}`"
              class="user-head"
              alt="用户头像加载失败!"
          />
          <p v-else class="linkNoAvatarHint">ta没有设置头像!</p>
        </div>
        <ul class="link-details">
          <li class="linkTargetItem">
            此链接指向: {{ l.data.linkPointer }}
          </li>
          <li class="linkProviderItem">
            链接提供方:{{ l.data.linksPublic ? '我们提供的' : '其他用户分享' }}
          </li>
          <li class="linkStateItem">
            <span class="linkStateText">当前链接状态: {{ getLinkStatic(l.data.linkState) }}</span>
            <br/>
            链接本体: <span class="linkBodyText">{{ l.data.link }}</span>
          </li>
          <li class="linkNotesItem">
            链接使用说明: <span class="linkNotesText">{{ l.data.notes }}</span>
          </li>
        </ul>
        <br/>
      </div>
      <ul class="link-usage-info">
        <li class="linkPrefixTitle">下面是您可能需要的网盘前缀信息:</li>
        <li v-for="(prefix, name) in linkPrefixMap" :key="name" class="link-item">
          {{ name }}前缀:
          <span class="link-text">{{ prefix }}</span>
          <button @click="copyToClipboard(prefix)" class="copy-btn">复制</button>
        </li>
      </ul>
    </div>
    <div v-else class="linkLocalContainer">
      <div class="linkLocalTotalCount">文件总数量为: {{ LinkList?.length ?? "暂无此信息,详见注释" }} 个</div>
      <div v-for="l in LinkList" :key="l.data.fileName" class="link">
        <div class="link-header">
          <span class="provider-name">本地资源提供者: {{ l.userName }}</span>
          <img
              v-if="!isNull(l.userHeadPortraitUrl)"
              :src="`${globalConst.staticResourceUrl}img/${l.userHeadPortraitUrl}`"
              class="user-head"
              alt="用户头像加载失败!"
          />
          <p v-else class="linkNoAvatarHint">ta没有设置头像!</p>
        </div>
        <ul class="link-details">
          <li class="linkDownloadItem">
            <label class="download-label">点击此按钮下载文件:{{ l.data.fileName }}<br>
              <button @click="down(<string> l.data.fileName)" class="download-btn">
                {{ l.data.fileName }}
              </button>
            </label>
          </li>
          <li class="linkLocalInfoItem">
            此资源为: {{ l.data.isPublic ? '我们提供的' : '其他用户分享' }}
          </li>
          <li class="linkLocalInfoItem">

            文件大小为: <span class="linkFileSizeText">{{ getSize(l.data.fileSize) }}</span>
          </li>
          <li class="linkLocalInfoItem">

            资源的注释信息:{{ isNull(l.data.notes) ? '还没录入注释信息呢' : l.data.notes }}
          </li>
          <li class="linkLocalInfoItem">

            本链接数量为:{{ l.data.size ? l.data.size : "暂无此信息,详见注释" }}
          </li>
        </ul>
        <br/>
      </div>
    </div>
  </div>
  <div v-else class="linkEmptyContainer">
    <p class="linkEmptyHint">暂无任何链接信息,请等待管理员录入</p>
  </div>
</template>

<script setup lang="ts">
import {defineProps} from "vue"
import {globalConst} from "@constants/globalConst.js"
import axiosInstance from "@utils/axiosInstance.js"
import {getToken} from "@stores/tokenStorage.js"
import {getUserToken} from "@stores/localStorage.js"
import {isNull} from "@utils/stringUtil.js"

interface LinkData {
  linkId?: string
  linkR?: string
  link?: string
  notes?: string
  linksPublic?: boolean
  isPublic?: boolean
  linkState?: string
  fileName?: string
  fileSize?: number
  size?: number
  linkPointer?: string
}

interface LinkItem {
  userName: string
  userHeadPortraitUrl?: string
  data: LinkData
}

export interface Props {
  LinkList: LinkItem[]
  hasLink: boolean
  isDown: boolean
  rId: number
}

const props = defineProps<Props>()
const {LinkList, hasLink, isDown, rId} = props
console.log(LinkList)
// 网盘前缀常量 → 合并成 map，便于循环渲染
const linkPrefixMap = {
  '百度网盘': "https://pan.baidu.com",
  '夸克网盘': "https://pan.quark.cn/s/",
  '微云网盘': "https://share.weiyun.com/",
  '阿里网盘': "https://www.aliyundrive.com/s/",
  'BT种子': "magnet:?xt=urn:btih:"
}

// 链接状态的映射表
const linkStateMap: Record<string, string> = {
  ok: "正常",
  instable: "不稳定",
  die: "链接失效"
}

// 获取链接状态
function getLinkStatic(linkState: string = ""): string {
  return linkStateMap[linkState] || "状态获取失败!"
}

// 复制链接到剪贴板（带兜底）
function copyToClipboard(text: string) {
  if (!text) return
  if (navigator.clipboard) {
    navigator.clipboard
        .writeText(text)
        .then(() => alert("链接已复制到剪贴板！"))
        .catch((err) => {
          console.error("复制失败:", err)
          fallbackCopy(text)
        })
  } else {
    fallbackCopy(text)
  }
}

function fallbackCopy(text: string) {
  const input = document.createElement("input")
  input.value = text
  document.body.appendChild(input)
  input.select()
  document.execCommand("copy")
  document.body.removeChild(input)
  alert("链接已复制到剪贴板！")
}

async function down(fileName: string) {
  if (isNull(fileName)) {
    alert("错误!你不能下载空文件!")
    return
  }
  try {
    const res = await axiosInstance.get(
        `${globalConst.baseUrl}user/download/rar?fileName=${fileName}&rId=${rId}`,
        {
          responseType: "blob",
          headers: {
            [globalConst.tokenName]: getUserToken(),
            [globalConst.userBuyToken]: getToken(globalConst.userBuyToken)
          }
        }
    )

    const contentType = res.headers["content-type"]

    if (contentType && contentType.includes("application/json")) {
      const text = await res.data.text()
      const json = JSON.parse(text)
      alert("下载失败! 原因是: " + json.msg)
      return
    }

    const blob = new Blob([res.data])
    const link = document.createElement("a")
    link.href = URL.createObjectURL(blob)
    link.download = fileName
    link.click()
    URL.revokeObjectURL(link.href)
  } catch (err) {
    console.error("下载失败:", err)
    alert("下载失败，请稍后再试！")
  }
}


// 文件大小格式化
function getSize(size: number = 0): string {
  const units = ["B", "KB", "MB", "GB", "TB"]
  let i = 0
  while (size >= 1024 && i < units.length - 1) {
    size /= 1024
    i++
  }
  return `${size.toFixed(2)} ${units[i]}`
}
</script>


<style scoped>
/* ======== 链接总容器 ======== */
.linkSection {
  width: 85%;
  margin: 2rem auto;
  padding: 1.5rem 2rem;
  border-radius: 16px;
  background: rgba(40, 0, 0, 0.35);
  backdrop-filter: blur(6px);
  box-shadow: 0 8px 30px rgba(255, 42, 109, 0.15);
  border: 1px solid rgba(255, 42, 109, 0.2);
  color: var(--text-primary);
  animation: fadeIn 0.8s ease-out;
}

/* ======== 外部链接与本地链接容器 ======== */
.linkExternalContainer,
.linkLocalContainer {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

/* ======== 单条链接卡片 ======== */
.link {
  background: rgba(50, 0, 0, 0.35);
  backdrop-filter: blur(4px);
  border-radius: 14px;
  padding: 1rem 1.5rem;
  border: 1px solid rgba(255, 42, 109, 0.25);
  box-shadow: 0 4px 16px rgba(255, 42, 109, 0.1);
  transition: all 0.3s ease;
}

.link:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-glow);
  border-color: rgba(255, 42, 109, 0.35);
}

/* ======== 头部信息（用户名 + 头像） ======== */
.link-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 0.8rem;
}

.provider-name {
  font-weight: 600;
  font-size: 1.1em;
  background: linear-gradient(135deg, var(--primary-red), var(--primary-purple));
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.user-head {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  border: 2px solid rgba(255, 42, 109, 0.4);
  object-fit: cover;
  box-shadow: 0 0 8px rgba(255, 42, 109, 0.2);
}

.linkNoAvatarHint {
  font-size: 0.9em;
  color: var(--text-secondary);
}

/* ======== 链接详细信息 ======== */
.link-details {
  list-style: none;
  padding-left: 0;
  margin: 0.5rem 0;
  display: flex;
  flex-direction: column;
  gap: 0.6rem;
}

.link-details li {
  font-size: 0.95em;
  color: var(--text-primary);
  line-height: 1.6;
}

.linkStateText {
  color: #ff9bb4;
  font-weight: bold;
}

.linkBodyText,
.linkNotesText,
.linkFileSizeText {
  color: #ffd8e4;
}

/* ======== 链接前缀信息区 ======== */
.link-usage-info {
  margin-top: 1.5rem;
  padding: 1rem;
  border-radius: 12px;
  background: rgba(20, 0, 0, 0.35);
  border: 1px solid rgba(255, 42, 109, 0.15);
  list-style: none;
}

.linkPrefixTitle {
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 0.6rem;
}

.link-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 0.4rem;
  font-size: 0.95em;
}

.link-text {
  color: #ffc9d6;
  margin-left: 0.5em;
}

/* ======== 通用按钮 ======== */
.copy-btn,
.download-btn {
  border: none;
  border-radius: 10px;
  padding: 0.4em 1em;
  background: linear-gradient(135deg, var(--primary-red), var(--primary-purple));
  color: var(--text-primary);
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-left: 0.5em;
}

.copy-btn:hover,
.download-btn:hover {
  transform: translateY(-1px);
  box-shadow: var(--shadow-glow);
}

/* ======== 本地下载信息区 ======== */
.linkLocalTotalCount {
  text-align: center;
  font-size: 1.1em;
  color: #ffd9df;
  margin-bottom: 1rem;
}

.download-label {
  display: flex;
  flex-direction: column;
  gap: 0.4rem;
}

/* ======== 空状态 ======== */
.linkEmptyContainer {
  padding: 3rem;
  text-align: center;
  color: var(--text-secondary);
}

.linkEmptyHint {
  font-size: 1.2em;
}

/* ======== 动画 ======== */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
